<template>
  <div class="banner" ref="banner">
    <van-swipe
      class="banner_swiper"
      v-if="validBannerList.length"
      :autoplay="4000"
      :show-indicators="false"
      indicator-color="white"
      @change="i => reportBannerPv(validBannerList[i])"
    >
      <van-swipe-item
        class="banner_swiper_item"
        v-for="(item, index) in validBannerList"
        @click="bannerJump(item)"
        :key="index"
      >
        <img v-lazy="item.imageUrl" alt="" class="banner_image" />
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script>
import reportMixin from '../mixins/report';
import jump from '../utils/jump';

export default {
  mixins: [reportMixin],

  props: {
    bannerList: {
      type: Array,
      default: () => []
    }
  },

  computed: {
    validBannerList() {
      return this.bannerList.filter(t => t);
    }
  },

  watch: {
    validBannerList: {
      immediate: true,
      handler: 'reportFirstBannerPv'
    }
  },

  methods: {
    bannerJump(obj) {
      this.maybeReportPv('ad_Banner_2', { ad_id: obj.id, position: 5 });
      if (obj.type !== 3) {
        // 跳转第三方链接
        if (obj && obj.pageType === 4 && !this.isInApp) {
          window.location.href = obj.url;
        } else {
          jump({ ...obj, lan: this.$store.getters.localeFull });
        }
      }
    },
    reportBannerPv(banner) {
      this.maybeReportPv('ad_Banner_1', { ad_id: banner.id, position: 5 });
    },
    reportFirstBannerPv(bannerList) {
      if (process.client) {
        this.$nextTick(() => {
          if (Array.isArray(bannerList) && bannerList.length) {
            this.reportBannerPv(bannerList[0]);
          }
        });
      }
    },
    maybeReportPv(...rest) {
      const { banner } = this.$refs;
      if (banner) {
        const rect = banner.getBoundingClientRect();
        if (rect.top + rect.height > 0) {
          this.report(...rest);
        }
      }
    }
  }
};
</script>

<style>
.banner_swiper,
.banner_swiper_item,
.banner_image {
  width: 694px;
  height: 232px;
  margin: auto;
}

.banner_image {
  display: block;
}

img[lazy=loading] {
  width: 694px;
  height: 232px;
  object-fit: cover;
}
</style>
